package com.geh.learn.hutool;

import com.google.common.io.BaseEncoding;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;

public class AESEncryptionDecryption {

    public static void main(String[] args) throws Exception {
        // 生成AES密钥
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey key = keyGen.generateKey();

       System.out.println(BaseEncoding.base64().encode(key.getEncoded()));

        // 准备需要加密的数据
        String data = "Hello, world!";
        byte[] dataBytes = data.getBytes("UTF-8");

        // 使用密钥对数据进行加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(dataBytes);

        // 使用密钥对数据进行解密
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(encryptedData);

        // 将解密后的数据转换为字符串
        String decryptedDataString = new String(decryptedData, "UTF-8");
        System.out.println("Decrypted data: " + decryptedDataString);
    }

}
